#include <string.h>
#include <stdint.h>

struct mime_entry {
  const char* name;
  const char* type;
};

static const struct mime_entry mime_tables[] = {{"any", "application/binary"}, /* default. */
                                                {"html", "text/html"},
                                                {"htm", "text/html"},
                                                {"css", "text/css"},
                                                {"txt", "text/plain"},
                                                {"pdf", "application/pdf"},
                                                {"gif", "image/gif"},
                                                {"png", "image/png"},
                                                {"jpeg", "image/jpeg"},
                                                {"jpg", "image/jpeg"},
                                                {"svg", "image/svg+xml"},
                                                {"avi", "video/x-msvideo"},
                                                {"mp3", "audio/mpeg"},
                                                {"ogg", "audio/x-oggvorbis"},
                                                {"wav", "audio/x-wav"},
                                                {"class", "application/octet-stream"},
                                                {"js", "application/x-javascript"},
                                                {"tar", "application/x-tar"},
                                                {"zip", "application/zip"},
                                                {"xml", "text/xml"},
                                                {"json", "application/json"},
                                                {NULL, NULL}};

static int str_end_with(const char* s, const char* t)
{
    const char* se;
    register int s_len, t_len;

    s_len = strlen(s);
    t_len = strlen(t);

    if (s_len < t_len) return 0;

    se = s + s_len - t_len;
    if (strncasecmp(se, t, t_len) == 0) return 1;

    return 0;
}

/**
 * get mime type according to URL
 */
const char* mime_get_type(const char* url) {
  uint32_t index;

  index = 0;
  if (url == NULL) {
    return mime_tables[0].type;
  }

  while (mime_tables[index].name != NULL) {
    if (str_end_with(url, mime_tables[index].name)) {
      return mime_tables[index].type;
    }

    index++;
  }

  /* return text/html as default */
  return mime_tables[1].type;
}
